"""
数据库连接模块
提供数据库连接和基本操作功能
"""

import pymysql
from typing import Dict, List, Optional
from app.utils.log_control import INFO, ERROR


class DatabaseConnection:
    """数据库连接类"""
    
    def __init__(self, config: Dict):
        """
        初始化数据库连接
        
        Args:
            config: 数据库配置信息
        """
        self.config = config
        self.connection = None
        
    def connect(self):
        """建立数据库连接"""
        try:
            if not self.connection or not self.connection.open:
                self.connection = pymysql.connect(
                    host=self.config['host'],
                    port=self.config['port'],
                    user=self.config['user'],
                    password=self.config['password'],
                    database=self.config['database'],
                    charset='utf8mb4',
                    cursorclass=pymysql.cursors.DictCursor
                )
                INFO.logger.info(f"数据库连接成功: {self.config['host']}:{self.config['port']}/{self.config['database']}")
        except Exception as e:
            ERROR.logger.error(f"数据库连接失败: {str(e)}")
            raise
            
    def execute_query(self, sql: str, params: Optional[Dict] = None) -> List[Dict]:
        """
        执行查询语句
        
        Args:
            sql: SQL查询语句
            params: 查询参数
            
        Returns:
            查询结果列表
        """
        try:
            self.connect()
            with self.connection.cursor() as cursor:
                cursor.execute(sql, params or {})
                result = cursor.fetchall()
                INFO.logger.info(f"执行查询成功: {sql[:100]}{'...' if len(sql) > 100 else ''}")
                return result
        except Exception as e:
            ERROR.logger.error(f"执行查询失败: {str(e)}, SQL: {sql[:100]}{'...' if len(sql) > 100 else ''}")
            return []
        finally:
            self.close()
            
    def execute_update(self, sql: str, params: Optional[Dict] = None) -> int:
        """
        执行更新语句
        
        Args:
            sql: SQL更新语句
            params: 更新参数
            
        Returns:
            受影响的行数
        """
        try:
            self.connect()
            with self.connection.cursor() as cursor:
                affected_rows = cursor.execute(sql, params or {})
                self.connection.commit()
                INFO.logger.info(f"执行更新成功: {sql}")
                return affected_rows
        except Exception as e:
            if self.connection:
                self.connection.rollback()
            ERROR.logger.error(f"执行更新失败: {str(e)}")
            return 0
        finally:
            self.close()
            
    def close(self):
        """关闭数据库连接"""
        if self.connection and self.connection.open:
            try:
                self.connection.close()
            except Exception as e:
                ERROR.logger.error(f"关闭数据库连接失败: {str(e)}") 